package com.hainabo.mgcmall.api;

import com.github.kristofa.brave.http.HttpServerRequest;
import com.hainabo.bootside.core.common.ReturnVO;
import com.hainabo.mgcmall.dao.Order;
import com.hainabo.mgcmall.dao.OrderRepository;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

@Api(value = "/order")
@Component
@Path("/order")
@Produces(MediaType.APPLICATION_JSON)
@Slf4j
public class OrderResource {

    @Autowired
    OrderRepository orderRepo;

    @GET
    @Path("/all")
    public ReturnVO all() {
        log.debug("");
        return new ReturnVO(orderRepo.findAll());
    }

    @POST
    @Path("/post")
    public ReturnVO post(Order order) {
        return new ReturnVO(orderRepo.save(order));
    }

    @GET
    @Path("/get/{id}")
    public ReturnVO findById(@Context HttpServerRequest request, @PathParam(value = "id") Long id) {
        log.debug("findById: {}", id);
        return new ReturnVO(orderRepo.findOne(id));
    }

    @DELETE
    @Path("/delete/{id}")
    public ReturnVO deleteById(@Context HttpServerRequest request, @PathParam(value = "id") Long id) {
        log.debug("deleteById: {}", id);
        if (orderRepo.findOne(id) != null) {
            orderRepo.delete(id);
            return new ReturnVO("ok");
        } else {
            return new ReturnVO(false, "not found");
        }
    }

    @PUT
    @Path("/put")
    public ReturnVO put(Order order) {
        log.debug("putOrder: {}", order);
        Order old = orderRepo.findOne(order.getId());
        if (old == null) {
            return new ReturnVO(ReturnVO.CODE_FAIL, ReturnVO.MSG_FAIL, "can't find the order");
        }
        BeanUtils.copyProperties(order, old);
        return new ReturnVO(orderRepo.save(order));
    }

}